package com.dfbz.controller.user;

import com.dfbz.common.Constant;
import com.dfbz.controller.BaseController;
import com.dfbz.model.User;
import com.dfbz.model.UserFocus;
import com.dfbz.service.DeptServices;
import com.dfbz.service.UserServices;
import com.dfbz.service.impl.DeptServicesImpl;
import com.dfbz.service.impl.UserServiceImpl;
import com.dfbz.utils.PageUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserController extends BaseController {

    private UserServices userServices = new UserServiceImpl();

    private DeptServices deptServices = new DeptServicesImpl();

    public void login(HttpServletRequest req, HttpServletResponse resp) {

        try {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String rememberme = req.getParameter("rememberme");


            User user = userServices.findByName(username);

            // 数据库找到用户
            if (null != user) {
                // 校验密码
                if (password.equals(user.getPassword())) {
                    // 登录成功
                    if (null != rememberme) {
                        // 而且勾选了"记住我"
                        // 将用户信息保存到cookie
                        Cookie cookie = new Cookie("uName", username);
                        cookie.setMaxAge(Constant.MAX_COOKIE_TIME);
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                    }
                    // 将用户的真实信息查出来
                    Map<String, Object> map = userServices.findUserBaseInfo(username);
                    req.getSession().setAttribute("userBaseInfo", map);
                    req.getSession().setAttribute("myUserId", map.get("user_id").toString());

                    // 还要更新登录时间
                    userServices.updateLoginTime(user.getId());
                    resp.sendRedirect(req.getContextPath() + "/assets/html/home.jsp");
                    return;
                } else {
                    req.getSession().setAttribute("loginMsg", "密码错误");
                }
            } else {
                req.getSession().setAttribute("loginMsg", "用户名不存在");
            }
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
//            req.getRequestDispatcher(req.getContextPath() + "/index.jsp").forward(req, resp);
//            req.getSession().removeAttribute("loginMsg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void register(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String password2 = req.getParameter("password2");
            boolean flag = userServices.checkByEmailOrName(email, username);
            if (!flag) {
                req.getSession().setAttribute("registerMsg", "该用户名或邮箱已被注册");
                resp.sendRedirect(req.getContextPath() + "/register.jsp");
            } else {
                if (password.equalsIgnoreCase(password2)) {
                    User user = new User();
                    user.setEmail(email);
                    user.setUsername(username);
                    user.setPassword(password);
                    boolean res = userServices.addUser(user);
                    if (res) {
                        // 添加成功，重定向回登录页
                        req.getSession().setAttribute("loginMsg", "注册成功");
                        resp.sendRedirect(req.getContextPath() + "/index.jsp");
                    } else {
                        req.getSession().setAttribute("registerMsg", "注册失败");
                        resp.sendRedirect(req.getContextPath() + "/register.jsp");
                    }
                } else {
                    req.getSession().setAttribute("registerMsg", "输入密码不一致");
                    resp.sendRedirect(req.getContextPath() + "/register.jsp");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void checkEmail(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            User user = userServices.findByEmail(email);
            String data = "0";
            if (null != user) {
                data = "1";
            }
            resp.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void checkUser(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String username = req.getParameter("username");
            User user = userServices.findByName(username);
            String data = "0";
            if (null != user) {
                data = "1";
            }
            resp.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendEmail(HttpServletRequest req, HttpServletResponse resp) {
        try {
            HttpSession session = req.getSession();
            String email = req.getParameter("email");
            User user = userServices.findByEmail(email);
            if (null == user) {
                resp.getWriter().write("该邮箱不存在");
            } else {
                // 发送邮件之前，看看会话是否过期
                Object value = session.getAttribute(email);
                if (null != value) {
                    // 生成验证码，发送给用户邮箱
                    String code = userServices.sendEmailCode(email);
                    if (code.length() == 4) {
                        // 发送成功,顺便将验证码保存到Session
                        session.setAttribute(email, code);
                        // 验证码保存五分钟
                        session.setMaxInactiveInterval(Constant.MAX_EMAIL_TIME);
                        resp.getWriter().write("邮件发送成功");
                    } else {
                        resp.getWriter().write("邮件发送失败，请重试");
                    }
                } else {
                    resp.getWriter().write("邮件已发送，请查收");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void reset(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            String code = req.getParameter("code");
            String password = req.getParameter("password");
            User user = userServices.findByEmail(email);
            if (null == user) {
                req.getSession().setAttribute("forgetMsg", "该邮箱账号不存在");
                resp.sendRedirect(req.getContextPath() + "/forget.jsp");
            } else {
                // 验证码校验
                Object value = req.getSession().getAttribute(email);
                if (null == value) {
                    req.getSession().setAttribute("forgetMsg", "验证码已过期");
                    resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                } else {
                    if (value.toString().equals(code)) {
                        // 相同，校验成功，可以重制密码
                        boolean res = userServices.resetPassword(email, password);
                        if (res) {
                            req.getSession().setAttribute("loginMsg", "密码重制成功");
                            resp.sendRedirect(req.getContextPath() + "/login.jsp");
                        } else {
                            req.getSession().setAttribute("forgetMsg", "重制失败");
                            resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                        }
                    } else {
                        req.getSession().setAttribute("", "验证码有误");
                        resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void look(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String userId = req.getParameter("userId");
            Map<String, Object> map = userServices.getUserInfo(userId);
            req.setAttribute("userinfo", map);
            req.setAttribute("deptList", deptServices.getAll());
            req.getRequestDispatcher("/assets/html/user_look.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                if ("uName".equals(cookie.getName())) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                    break;
                }
            }
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getUsers(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String page = req.getParameter("page");
            String name = req.getParameter("searchName");
            int currentPage = 1;
            if (null != page) {
                currentPage = Integer.parseInt(page);
            }
            // 从会话拿到当前登录的账号信息
            Map baseInfo = (Map) req.getSession().getAttribute("userBaseInfo");
            String userId = baseInfo.get("user_id").toString();
            List<Map<String, Object>> userList = userServices.getUserList(userId, currentPage, name);
            req.setAttribute("userList", userList);
            long totalCount = userServices.getUserCount(name);
            long totalPage = PageUtil.getTotalPage(totalCount);
            long startPage = PageUtil.getStartPage(currentPage);
            long endPage = PageUtil.getEndPage(currentPage, totalCount);
            req.setAttribute("currentPage", currentPage);
            req.setAttribute("searchName", name);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("pageCount", Constant.PAGE_COUNT);
            req.setAttribute("startPage", startPage);
            req.setAttribute("endPage", endPage);
            req.getRequestDispatcher("/assets/html/user.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void followUser(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String data;
            String ufId = req.getParameter("ufId");
            String userId = getUserId(req);
            if (userId.equals(ufId)) {
                data = "不能关注自己";
            } else {
                // 检查有没有重复关注
                UserFocus focus = userServices.getFollowUser(userId, ufId);
                if (null != focus) {
                    // 说明之前关注过，不能重复关注
                    data = "不能重复关注";
                } else {
                    boolean b = userServices.followUser(userId, ufId);
                    if (b) {
                        data = "1";
                    } else {
                        data = "关注失败";
                    }
                }
            }
            resp.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void unFollowUser(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String data;
            String ufId = req.getParameter("ufId");
            String userId = getUserId(req);
            UserFocus focus = userServices.getFollowUser(userId, ufId);
            if (null != focus){
                boolean b = userServices.unFollowUser(focus.getId());
                if (b){
                    data = "1";
                } else {
                    data = "取消关注失败";
                }
            }else {
                data = "未关注过，无法取消";
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
